package com.fingersoft.dexload;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.fingersoft.im.BuildConfig;

import static android.content.Context.MODE_MULTI_PROCESS;

/**
 * @author：jooper Email：jooperge@163.com
 * 描述：最好仅在主进程使用
 * 修改历史:
 * <p>
 * 创建于： 2019-07-28
 */
public class LunchModeHelper {
    /**
     * 启动-模式,首次安装-首次启动
     */
    public static final int LMODE_NEW_INSTALL = 1;
    /**
     * 覆盖安装-首次启动
     */
    public static final int LMODE_UPDATE = 2;
    /**
     * 已安装-二次启动
     */
    public static final int LMODE_AGAIN = 3;

    private boolean isOpenMarked = false;
    private int launchMode = LMODE_AGAIN;

    private static LunchModeHelper instance;

    private SharedPreferences share;

    public static LunchModeHelper getInstance() {
        if (instance == null) {
            instance = new LunchModeHelper();
        }

        return instance;
    }

    public void markOpenApp(Application application, boolean force) {
        // 防止-重复调用
        if (isOpenMarked && !force) {
            return;
        }
        isOpenMarked = true;

        share = application.getSharedPreferences("applaunchmode", MODE_MULTI_PROCESS);
        String lastVersion = share.getString("lastVersion", "");
        String thisVersion = String.valueOf(BuildConfig.VERSION_CODE);

        if (TextUtils.isEmpty(lastVersion)) {
            launchMode = LMODE_NEW_INSTALL;
            share.edit().putString("lastVersion", thisVersion).commit();
        } else if (!thisVersion.equals(lastVersion)) {
            launchMode = LMODE_UPDATE;
            share.edit().putString("lastVersion", thisVersion).commit();
        } else {
            launchMode = LMODE_AGAIN;
        }
    }

    public void clearLastVersion(Context context) {
        if (null == share) {
            share = context.getSharedPreferences("applaunchmode", MODE_MULTI_PROCESS);
        }
        launchMode = LMODE_NEW_INSTALL;
        share.edit().putString("lastVersion", "").commit();
    }

    public int getLaunchMode() {
        return launchMode;
    }

    // 首次打开,新安装、覆盖(版本号不同)
    public boolean isFirstOpen() {
        return launchMode != LMODE_AGAIN;
    }
}
